package fr.univ.context.utilities;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import android.content.Context;
import android.os.Environment;
import android.util.Log;

// Class to export the current database to the SDcard.
public class BackupDB {
  
	private static final String TAG = "Exec";
	private static FileInputStream fileInputStream;
	private static FileOutputStream fileOutStream;

  public static boolean writeToSD(Context context) {
	  
    try {
      
    	File sd = Environment.getExternalStorageDirectory();

    	if (sd.canWrite()) {
    		
	        String filePath = new String(Constants.MAIN_PACKAGE.substring(Constants.MAIN_PACKAGE.lastIndexOf('.') + 1));
	        File extDBDir = new File(sd, filePath);
	        File extDBFile = new File(sd, filePath + "/" + Constants.BACKUP_DATABASE_NAME);

	        if (!extDBDir.exists()) {
	           // Creating directory: extDBDir.getAbsolutePath()
	          if (!extDBDir.mkdir()) {
	            Log.e(TAG, "Directory creation failed.");
	          }
	        } else {
	          Log.d(TAG, "writeToSD: Directory creation skipped.");
	        }
	
	        try {
	          // Creating new file: extDBFile.getAbsolutePath());
	          extDBFile.createNewFile();
	        } catch (IOException e) {
	          Log.d(TAG, "writeToSD: " + e.toString());
	        } catch (SecurityException e) {
	          Log.d(TAG, "writeToSD: " + e.toString());
	        }
	
	        fileOutStream = new FileOutputStream(extDBFile);
	        fileInputStream = new FileInputStream(context.getDatabasePath(Constants.DATABASE_NAME));
	
	        // Transfer bytes from the input file to the output file
		    byte[] buffer = new byte[1024];
		    int length;
		    while ((length = fileInputStream.read(buffer))>0){
		        fileOutStream.write(buffer, 0, length);
		    } 
	       
	        fileOutStream.flush();
	        // Closed file.
	        fileOutStream.close();
	
	        extDBFile = new File(sd, filePath + "/" + Constants.BACKUP_DATABASE_NAME);
	        
	        if (!extDBFile.exists())
	          Log.e(TAG, "Downloaded file doesn't exist.");
	        
	        if (extDBFile.length() != buffer.length)
	          Log.e(TAG, "Downloaded file doesn't match size.");
	        else
	          Log.v(TAG, "File on SD card is size: "
	                  + extDBFile.length());
	     
	        return true;
      }
    	
    } catch (Exception e) {
      Log.e(TAG, "WriteToSD threw exception: " + e.toString());
    }
    return false;
  }

  /**
   * @param filename */
  public static void makeReadOnly(String filename) {
    File file = new File(filename);
    
    if (!file.exists())
      return;
    
    file.setReadOnly();
  }
}